package main

import (
	"context"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"go.manyji.com/lib/log"
	"go.manyji.com/lib/util/convert"
	"reflect"
	"strings"
	"time"
)

func (a *data_IncomeStatistics) Query(ctx context.Context, uid uint64, pp PaginationParam, queryConditions []string) interface{} {

	queryConditions = append(queryConditions, []string{
		"income_statistics.deleted = 0",
		fmt.Sprintf("income_statistics.leader_id = %v", uid),
	}...)

	var (
		condition = fmt.Sprintf(`
WHERE %v`, strings.Join(queryConditions, " AND "))
		queryCountSQL = fmt.Sprintf(`
	SELECT 
	    COUNT(*)  as count
	FROM income_statistics
		%v
`, condition)
		querySQL = fmt.Sprintf(`
SELECT
  income_statistics.id AS id,
  income_statistics.date AS date,
  income_statistics.business_type_id AS business_type_id,
  income_statistics.business_type_desc AS business_type_desc,
  income_statistics.points_consume AS points_consume,
  income_statistics.points_consume_account AS points_consume_account,
  income_statistics.points_consume_gift AS points_consume_gift,
  income_statistics.agent_points AS agent_points,
  income_statistics.profit AS profit,
  income_statistics.task_nums AS task_nums,
  income_statistics.task_nums_valid AS task_nums_valid,
  income_statistics.sieve_source_name AS sieve_source_name,
  income_statistics.account_id AS account_id,
  income_statistics.leader_id AS leader_id,
  income_statistics.leader_name AS leader_name,
  income_statistics.create_at AS create_at,
  income_statistics.updated_at AS updated_at,
  income_statistics.deleted AS deleted
FROM income_statistics
%v 
ORDER BY income_statistics.create_at DESC
%v 
`, condition, fmt.Sprintf(" LIMIT %v OFFSET %v", pp.PageSize, (pp.PageIndex-1)*pp.PageSize))
	)

	log.Info("query sql ", querySQL)
	respCount, err := db.QueryRaw(ctx, queryCountSQL, QueryCount{})
	if err != nil {
		return err
	}

	if respCount == nil {
		return nil
	}

	count := respCount[0].(*QueryCount).Count

	respTaskList, err := db.QueryRaw(ctx, querySQL, IncomeStatistics{})
	if err != nil {
		return err
	}

	ret := map[string]interface{}{
		"list":  respTaskList,
		"total": count,
	}

	if ret != nil {

		var (
			t = IncomeStatistics{}
		)
		for _, v := range ret["list"].([]interface{}) {

			respIS := v.(*IncomeStatistics)
			t.PointsConsume += respIS.PointsConsume
			t.PointsConsumeAccount += respIS.PointsConsumeAccount
			t.PointsConsumeGift += respIS.PointsConsumeGift
			t.TaskNums += respIS.TaskNums
			t.TaskNumsValid += respIS.TaskNumsValid
			t.AgentPoints += respIS.AgentPoints
			t.Profit += respIS.Profit
		}

		ret["all"] = map[string]interface{}{
			"points_consume":         t.PointsConsume,
			"points_consume_account": t.PointsConsumeAccount,
			"points_consume_gift":    t.PointsConsumeGift,
			"task_nums":              t.TaskNums,
			"task_nums_valid":        t.TaskNumsValid,
			"agent_points":           t.AgentPoints,
			"profit":                 t.Profit,
		}
	}

	return ret
}

func (a *data_IncomeStatistics) Export(ctx context.Context, uid uint64, item map[string]interface{}) interface{} {

	var (
		condition = fmt.Sprintf(`
WHERE income_statistics.deleted = 0 AND income_statistics.id IN (%v)
`, strings.Join(strings.Split(item["ids"].(string), "|"), ","))
		querySQL = fmt.Sprintf(`
SELECT
  income_statistics.id AS id,
  income_statistics.date AS date,
  income_statistics.business_type_id AS business_type_id,
  income_statistics.business_type_desc AS business_type_desc,
  income_statistics.points_consume AS points_consume,
  income_statistics.points_consume_account AS points_consume_account,
  income_statistics.points_consume_gift AS points_consume_gift,
  income_statistics.profit AS profit,
  income_statistics.task_nums AS task_nums,
  income_statistics.task_nums_valid AS task_nums_valid,
  income_statistics.account_id AS account_id,
  income_statistics.leader_id AS leader_id,
  income_statistics.leader_name AS leader_name,
  income_statistics.create_at AS create_at,
  income_statistics.updated_at AS updated_at,
  income_statistics.deleted AS deleted
FROM income_statistics
%v
`, condition)
	)

	resp, err := db.QueryRaw(ctx, querySQL, IncomeStatistics{})
	if err != nil {
		return err
	}

	selectedItems := []string{
		"date",
		"business_type_desc",
		"points_consume",
		"points_consume_account",
		"points_consume_gift",
		"profit",
		"task_nums",
		"task_nums_valid",
	}
	req := a.export(ctx, resp, strings.Join(selectedItems, "|"))
	if req != nil {
		if _, ok := req.(error); ok {
			return req
		}
	}

	return req
}

func (a *data_IncomeStatistics) export(ctx context.Context, req interface{}, selectedItems string) interface{} {

	var (
		selectedItemMap = make(map[string]int)
		xlsx            = excelize.NewFile()
		categories      = map[string]string{"A1": "日期", "B1": "业务类型", "C1": "消耗积分", "D1": "账户消耗", "E1": "赠送消耗", "F1": "利润", "G1": "任务数", "H1": "有效数"}
		colWidths       = map[string]float64{"A": 18, "B": 20, "C": 20, "D": 20, "E": 20, "F": 20, "G": 12, "H": 12}
	)

	for key, value := range categories {
		xlsx.SetCellValue("Sheet1", key, value)
		_style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["#EEECE1"],"pattern":1},"alignment":{"horizontal":"center","vertical":"center"},"font":{"bold":true,"family":"宋体","size":10}}`)
		if err == nil {
			xlsx.SetCellStyle("Sheet1", key, key, _style)
		}
	}

	for k, v := range colWidths {
		xlsx.SetColWidth("Sheet1", k, k, v)
	}

	for i, v := range strings.Split(fmt.Sprintf("%v", selectedItems), "|") {
		selectedItemMap[v] = i
	}

	p := map[string]struct{}{
		"points_consume":         {},
		"points_consume_account": {},
		"points_consume_gift":    {},
		"profit":                 {},
	}

	for index, vv := range req.([]interface{}) {

		var (
			columIndex  = 'A'
			columOffset = 1
		)
		for kkk, vvv := range Struct2Map(vv, "json") {

			if len(selectedItemMap) > 0 {
				if i, ok := selectedItemMap[kkk]; !ok {
					continue
				} else {
					columOffset = i
				}
			}

			cell := fmt.Sprintf("%c", int(columIndex)+columOffset) + convert.ToString(index+2)

			if reflect.TypeOf(vvv).Kind() == reflect.Ptr {
				vOf := reflect.ValueOf(vvv)
				if vOf.IsNil() {
					vvv = ""
				} else {
					vvv = vOf.Elem()
				}
			}

			if _, ok := p[kkk]; ok {
				vvv = Decimal(float64(vvv.(uint64))/10000.0, 5)
			}
			xlsx.SetCellValue("Sheet1", cell, vvv)
		}
		xlsx.SetRowHeight("Sheet1", index+2, 18)
	}

	xlsx.SetSheetName("Sheet1", "第一页")

	filPath, fileName := a.getExportPath(convert.ToString(time.Now().UnixMilli())+".csv", 1)
	err := xlsx.SaveAs(filPath)
	if err != nil {
		return err
	}

	ret := fileName

	return ret
}

func (a *data_IncomeStatistics) getExportPath(fileName string, bizTy int) (string, string) {

	var (
		bizTyMap = map[int]string{
			1: "income",
		}
	)

	relativePath := fmt.Sprintf("%v/export/%v", bizTyMap[bizTy], fileName)

	return GetFilePath(
		fmt.Sprintf("%v/%v",
			FileStorage,
			relativePath),
	), relativePath
}
